const db = require("../db")
const bcrypt = require('bcryptjs')
const date = require("silly-datetime");
const today = date.format(new Date(),'YYYY-MM-DD HH:mm:ss'); 
exports.detail=(req,res)=>{
   const id = req.body.id
   db.query("select user.id,username,nickName,email,userPic,roleId,role.roleName,phone from user,role where user.id = ? and user.roleId = role.id",id,function(err,result){
        if(err) return res.cc(err)
        if(result.length !== 1) return res.cc("获取用户信息失败！",-1)
        return res.send({
            code:200,
            msg:'获取用户信息成功',
            data:result[0]
        })
    })
}
exports.updateInfo = (req,res)=>{
    const newInfo = req.body
    newInfo['updateTime'] = today
    let sql = `update user set nickName = ? , email = ?, updateTime=? ,roleId = ? where id = ?`
    db.query(sql,[newInfo.nickname,newInfo.email,today,newInfo.roleId,newInfo.id],function(err,result){
        if(err) return res.cc(err)
        if(result.affectedRows != 1) return res.cc("用户信息更新失败！",-1)
        return res.cc("用户信息更新成功",200)
    })
}

exports.changePWD = (req,res)=>{
    const newInfo = req.body
    newInfo.password = bcrypt.hashSync(newInfo.password,10)
    db.query("update user set password = ?,updateTime = ? where id = ?",[newInfo.password,today,newInfo.id],function(err,result){
        if(err) return res.cc(err)
        if(result.affectedRows != 1) return res.cc("更新密码失败！",-1)
        return res.cc("更新密码成功！",200)
    })
}
exports.updateAvatar = (req,res)=>{
    const newInfo = req.body
    db.query("upate user set userPic = ?,updateTime = ? where id = ? ",[newInfo.url,today,newInfo.id],function(err,result){
        if(err) return res.cc(err)
        if(result.affectedRows != 1) return res.cc("用户头像更新失败！",-1)
        return res.cc("用户头像更新成功！",200)
    })

}

exports.selectAll = (req,res) =>{
    let quryInfo = req.body
    let num = quryInfo.num
    let page = quryInfo.page
    let name = quryInfo.query
    let str = `select user.id, username,nickName,email,user.createTime,roleId,phone,role.roleName,mg_state from user,role where user.roleId = role.id and 1=1`
    if(name != ''){
        str += ' and username like "%'+name+'%"'
    }
    str+=  ` order by user.createTime desc limit ${parseInt(num*(page - 1))},${page*num};select count(*) as total from user,role where user.roleId = role.id;`
    db.query(str,function(err,result){
        if(err) return res.cc(err)
        for(let i = 0 ; i <result[0].length;i++){
            if(result[0][i].mg_state == '1'){
                result[0][i].mg_state = true
            }else{
                result[0][i].mg_state = false
            }
        }
        return res.send({
            code:200,
            msg:"查询用户列表成功！",
            count:result[1][0].total,
            data:[...result[0]]
        })
    })
}
/**
 * 随机生成字符串
 * @param len 指定生成字符串长度
 */
 function getRandomString(len){
    let _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789',
        min = 0, 
        max = _charStr.length-1, 
        _str = '';                    //定义随机字符串 变量
    //判断是否指定长度，否则默认长度为15
    len = len || 15;
    //循环生成字符串
    for(var i = 0, index; i < len; i++){
        index = (function(randomIndexFunc, i){         
                    return randomIndexFunc(min, max, i, randomIndexFunc);
                })(function(min, max, i, _self){
                    let indexTemp = Math.floor(Math.random()*(max-min+1)+min),
                        numStart = _charStr.length - 10;
                    if(i==0&&indexTemp >=numStart){
                        indexTemp = _self(min, max, i, _self);
                    }
                    return indexTemp ;
                }, i);
        _str += _charStr[index];
    }
    return _str;
}
 
exports.addUser = (req,res) =>{
    const newUser = req.body
    newUser['createTime'] = today
    newUser['is_delete'] = 0
    newUser['username'] = getRandomString(10);
    newUser.password = bcrypt.hashSync(newUser.password,10)
    db.query("insert into user set ? ",newUser,function(err,result){
        if(err) return res.cc(err)
        if(result.affectedRows !== 1) return res.cc("新增用户失败！")
        return res.send({
            code:200,
            msg:'新增用户成功'
        })
    })
}

exports.updateState = (req,res) =>{
    let id = req.body.id
    let state = req.body.state
    let sql =`update user set mg_state = ${state} where id = ${id}`
    db.query(sql,function(err,result){
        if(err) return res.cc(err)
        if(result.affectedRows != 1) return res.cc("修改用户状态失败！")
        return res.cc("修改用户状态成功！",200)
    })
}